package models

import (
	"time"
	
	"gorm.io/gorm"
)

type Post struct {
	ID          uint      `gorm:"primaryKey" json:"id"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	Title       string    `gorm:"size:255;not null" json:"title"`
	Slug        string    `gorm:"size:255;uniqueIndex;not null" json:"slug"`
	Content     string    `gorm:"type:text;not null" json:"content"`
	Excerpt     string    `gorm:"size:255" json:"excerpt"`
	CoverImage  string    `gorm:"size:255" json:"cover_image"`
	UserID      uint      `gorm:"not null" json:"user_id"`
	User        User      `gorm:"foreignKey:UserID" json:"user"`
	CategoryID  uint      `gorm:"not null" json:"category_id"`
	Category    Category  `gorm:"foreignKey:CategoryID" json:"category"`
	Status      int       `gorm:"default:0" json:"status"` // 0: draft, 1: published
	PublishedAt time.Time `json:"published_at,omitempty"`
	Comments    []Comment `gorm:"foreignKey:PostID" json:"comments,omitempty"`
	Tags        []Tag     `gorm:"many2many:post_tags;" json:"tags,omitempty"`
	ViewCount   int       `gorm:"default:0" json:"view_count"`
}

// 钩子函数 - 创建前生成时间戳
func (p *Post) BeforeCreate(tx *gorm.DB) (err error) {
	p.CreatedAt = time.Now()
	p.UpdatedAt = time.Now()
	if p.Status == 1 && p.PublishedAt.IsZero() {
		p.PublishedAt = time.Now()
	}
	return
}

// 钩子函数 - 更新前更新时间戳
func (p *Post) BeforeUpdate(tx *gorm.DB) (err error) {
	p.UpdatedAt = time.Now()
	if p.Status == 1 && p.PublishedAt.IsZero() {
		p.PublishedAt = time.Now()
	}
	return
}